package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.Banner;
import com.itheima.domain.BannerExample;
import com.itheima.mapper.BannerMapper;
import com.itheima.service.BannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class BannerServiceImpl implements BannerService {

    @Autowired
    private BannerMapper bannerMapper;

    @Override
    public PageInfo<Banner> findByPage(Integer pageNum, Integer pageSize) {
        //设置分页查询条件
        PageHelper.startPage(pageNum,pageSize);
        //设置排序条件
        BannerExample bannerExample = new BannerExample();
        bannerExample.setOrderByClause("order_no desc");

        //查询所有
        List<Banner> list = bannerMapper.selectByExample(bannerExample);
        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<Banner> findByPage(Integer pageNum, Integer pageSize, String title) {
        //设置分页查询条件
        PageHelper.startPage(pageNum,pageSize);
        //设置排序条件
        BannerExample bannerExample = new BannerExample();
        bannerExample.setOrderByClause("order_no desc");
        BannerExample.Criteria criteria = bannerExample.createCriteria();

        //设置查询条件
        if (title!=null && !"".equals(title)){
            criteria.andTitleLike("%"+title+"%");
        }

        //查询所有
        List<Banner> list = bannerMapper.selectByExample(bannerExample);
        return new PageInfo<>(list);
    }

    @Override
    public void save(Banner banner) {
        //获取id
        Integer id = banner.getId();
        if (id==null){
            bannerMapper.insertSelective(banner);
        }else{
            bannerMapper.updateByPrimaryKeySelective(banner);
        }
    }

    @Override
    public Banner findById(Integer id) {
        return bannerMapper.selectByPrimaryKey(id);
    }

    @Override
    public void deleteById(Integer id) {
        bannerMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteBatch(Integer[] ids) {
        for (Integer id : ids) {
            bannerMapper.deleteByPrimaryKey(id);
        }
    }
}
